#coding: utf-8
from django import forms
from django.forms import ModelForm
from django.forms.util import ErrorList 
from resources.models import Resource

class AddResourceForm( ModelForm ):
    class Meta:
        model = Resource
        exclude = ( 'digg' )

    def clean( self ):
        cleaned_data = self.cleaned_data
        type = cleaned_data.get( 'type' )
        content = cleaned_data.get( 'content' )
        url = cleaned_data.get( 'url' )
        description = cleaned_data.get( 'description' )
        if ( type == '4' ) and ( content == u'' ):
            msg = u'类型是Text时,内容必填！' 
            self._errors[ 'content' ] = ErrorList([msg])
            del cleaned_data[ 'content' ]
        if ( type in [ '1', '2', '3' ] ) and ( url == u'' ):
            msg = u'类型是Article、Image或Video时，URL必填！' 
            self._errors[ 'url' ] = ErrorList([msg])
            del cleaned_data[ 'url' ]
        if ( type in [ '1', '2', '3' ] ) and ( description == u'' ):
            msg = u'类型是Article、Image或Video时，描述必填！' 
            self._errors[ 'description' ] = ErrorList([msg])
            del cleaned_data[ 'description' ]
        if ( url != u'' ) and Resource.objects.filter(url=url):
            msg = u'URL不唯一！'
            self._errors[ 'url' ] = ErrorList([msg])
            del cleaned_data[ 'url' ]
        return cleaned_data